import React, { useRef, useState, useEffect } from "react";
import { Empty, Tree, Spin, Modal } from "antd";
import { PlusOutlined } from "@ant-design/icons";
const { DirectoryTree } = Tree;
import styled from "styled-components";
import { useNavigate, useParams } from "react-router-dom";
import { downloadFile, getFileType } from "../utils/file-helper";
import { newFileMap } from "../services/graphql";
import { fileDetail, getContainerTree, newContainer } from "../services/suture";
import { formatPicUrl, formatterSizeStr } from "../utils/formatter";
import * as antdHelper from "../utils/antd-helper";
import webconfig from "../webconfig";
import copy from "copy-to-clipboard";
import store from "../utils/store";
import DocViewer, { DocViewerRenderers } from "@cyntler/react-doc-viewer";
import "@cyntler/react-doc-viewer/dist/index.css";

let treeSelectId = 0;
let selectItem = null;
let timeout = null;
let selectFolder = null;
let folderName = '';

function Main({ className, fileInfo, fid, shareid, onNavBack }) {
	const navigate = useNavigate();
	const [detail, setDetail] = useState({});
	const [inputName, setInputName] = useState("");
	const [isLoading, setIsLoading] = useState(false);
	const [isSaving, setIsSaving] = useState(false);
	const [owner, setOwner] = useState("No found");
	const [isLogin, setIsLogin] = useState(false);
	const [showSaveToMeBox, setShowSaveToMeBox] = useState(false);
	const [showCreateFolderBox, setShowCreateFolderBox] = useState(false);
	const [folderTree, setFolderTree] = useState();
	const [menuShow, setMenuShow] = useState(false);
	const [menuPoint, setMenuPoint] = useState({ top: 0, left: 0 });

	const init = async () => {
		setIsLoading(true);
		let hasLogin = store.get("token") ? true : false;
		setIsLogin(hasLogin);
		let ret = await fileDetail(fid, shareid);
		// console.log({ ret });
		setIsLoading(false);
		if (ret.msg == "ok" && ret.data) {
			ret.data.fileType = getFileType(ret.data.fileName);
			ret.data.fileUrl = formatPicUrl(ret.data.fid);
			if (ret.data.fileSize && !ret.data.fileSizeStr) {
				ret.data.fileSizeStr = formatterSizeStr(ret.data.fileSize);
			}
			let cessAddr = store.get("cess-addr");
			console.log("myAddr", cessAddr, "owner", ret.data.owner);
			ret.data.isMyOwner = ret.data.owner?.find(t => t.user == cessAddr) ? true : false;
			if (ret.data.uploadTime) {
				ret.data.uploadDate = ret.data.uploadTime.split(' ')[0].replace("-", "/").replace("-", "/");
			}
			setDetail(ret.data);
			let o = ret.data.owner[0];
			if (o.user) {
				setOwner(o.user);
			} else {
				let address = store.get("address");
				if (address) setOwner(address);
			}
		}
	};
	useEffect(() => {
		console.log(fileInfo);
		init();
	}, [fid, shareid]);
	const onShare = () => {
		antdHelper.shareFile(window.location.origin + "/share/" + detail.shareLink);
	};
	const onDownload = async () => {
		let url = formatPicUrl(detail.fid);
		url = url.replace("open", 'download');
		downloadFile(url, detail.title);
	};
	const onGoback = () => {
		if (onNavBack) {
			return onNavBack();
		}
		navigate(-1);
	}

	//move file
	const onShowSaveBox = async () => {
		setInputName(detail.title);
		let ret = await getContainerTree();
		if (ret.msg != 'ok') return;
		setFolderTree(ret.tree);
		setShowSaveToMeBox(true);
	};
	const onTreeSelect = (keys, info) => {
		selectItem = info.selectedNodes[0];
	};
	const onInputName = e => {
		let v = e.target.value;
		setInputName(v);
	};
	const onInputFolderName = e => {
		folderName = e.target.value;
	};
	const saveToMyFile = async () => {
		if (!selectItem) {
			return antdHelper.alertError("Select a folder please.");;
		}
		if (!inputName) {
			return antdHelper.alertError("File name is a required.");;
		}
		console.log({ selectItem });
		antdHelper.loading("loading");
		setIsSaving(true);
		let ret = await newFileMap(detail.fid, inputName, selectItem.territoryId, selectItem.id);
		if (ret && ret.msg == "ok") {
			detail.isMyOwner = true;
			setDetail(detail);
			antdHelper.notiOK("Save to my file success");
		}
		setIsSaving(false);
		antdHelper.loading();
		setShowSaveToMeBox(false);
	};
	const onRightClick = ({ event, node }) => {
		console.log({ event, node });
		selectFolder = node;
		setMenuPoint({ top: event.clientY - 233, left: event.clientX - 233 });
		setMenuShow(true);
	}
	const onMenuOver = () => {
		clearTimeout(timeout);
		setMenuShow(true);
	}
	const onMenuOut = () => {
		timeout = setTimeout(function () {
			setMenuShow(false);
		}, 500);
	}
	const onCreateFolderSubmit = async () => {
		let dir = { id: 0 };
		if (selectFolder.territoryId) {
			dir.id = selectFolder.id;
		}
		let ret = await newContainer(dir, selectFolder.territoryId || selectFolder.id, folderName, setIsSaving);
		if (ret.msg != 'ok') return;
		setShowCreateFolderBox(false);
		ret = await getContainerTree();
		if (ret.msg != 'ok') return;
		setFolderTree(ret.tree);
	}

	return (
		<div className={className}>
			{onNavBack && <div className="btn-back" onClick={onGoback}></div>}
			<Spin spinning={isLoading}>
				{detail && detail.fid ? (
					<div className="con">
						{detail.fileType == "video" ? (
							<div className="video-box">
								<video style={{ backgroundColor: "#000", maxHeight: 750 }} autoPlay={true} width="100%" height="100%" controls>
									<source src={detail.fileUrl} type="video/mp4" />
								</video>
								<div className="video-msg">Connecting CESS Network. Data from {webconfig.gatewayAddr}</div>
							</div>
						) : detail.fileType == "music" ? (
							<div className="music-box">
								<div className="cp">
									<img width={150} height={150} src={detail.fileUrl} />
								</div>
								<audio id="music3" controls>
									<source src={detail.fileUrl}></source>
								</audio>
							</div>
						) : detail.fileType == "image" ? (
							<div className="image-box">
								<img src={detail.fileUrl} />
							</div>
						) : detail.fileType == "application" ? (
							<div className="app-box">
								<div></div>
							</div>
						) : detail.fileType == "document" ? (
							<div className="app-box333">
								<DocViewer documents={[{uri:detail.fileUrl,fileName: detail.fileName}]} prefetchMethod="GET" pluginRenderers={DocViewerRenderers} />
								{/* <iframe src={detail.fileUrl} style={{ width: "100%", minHeight: 1000 }} /> */}
							</div>
						) : (
							<div className="unknow-box">
								<div></div>
							</div>
						)}


						<div className="title">{detail.title || detail.fileName}</div>
						<div className="auther-box">
							<div className="avtho">{owner?.slice(0, 1)}</div>
							<div className="addr">{owner}</div>
							<div className="btns">
								{isLogin && !detail.isMyOwner && (
									<span className="btn1" onClick={onShowSaveBox}>
										Save to My Files
									</span>
								)}
								<span className="btn2" onClick={onDownload}>
									Download
								</span>
								{detail.shareLink && <span className="btn3" onClick={onShare}>
									Share
								</span>}
							</div>
						</div>
						<div className="more-info">
							<div className="l1">
								{detail.fileSizeStr} &nbsp;&nbsp;<font>Created in {detail.uploadDate}</font>
							</div>
							<div className="l2">FID: {detail.fid} </div>
							<div className="l3">file type: {detail.fileExt || detail.fileType}</div>
						</div>
					</div>
				) : (
					<Empty />
				)}
			</Spin>
			<Modal width={800} title="" open={showSaveToMeBox} footer={null} onCancel={() => setShowSaveToMeBox(false)}>
				<Spin spinning={isSaving}>
					<div className="mypopu">
						<div className="title">Save to My Files</div>
						<div className="con">
							<div className="tree-box">
								{
									menuShow && <div className="content-menu" style={{ top: menuPoint.top, left: menuPoint.left }} onMouseOver={onMenuOver} onMouseOut={onMenuOut}>
										<span className="menu-item" onClick={() => setShowCreateFolderBox(true)}> <PlusOutlined /> Create Children Folder</span>
									</div>
								}

								<DirectoryTree multiple defaultExpandAll onSelect={onTreeSelect} treeData={folderTree} onRightClick={onRightClick} />
							</div>
							<div><div style={{ lineHeight: "46px" }}>File Name:</div>
								<input value={inputName} style={{ width: "96%", padding: "0 2%", borderRadius: 48, height: 48, lineHeight: 48, border: "1px solid rgb(195, 195, 195)", backgroundColor: "transparent", outline: "none" }} onInput={onInputName} onKeyUp={onInputName} onChange={onInputName} className="input1" type="text" placeholder="Less than 63 characters" />
							</div>
						</div>
						<div className="footer">
							<span className="btn btn-primary" onClick={saveToMyFile}>
								Confirm
							</span>
							<span onClick={() => setShowSaveToMeBox(false)} className="btn btn-default">
								Cancel
							</span>
						</div>
					</div>
				</Spin>
			</Modal>
			<Modal width={400} height={80} title="Create Folder" open={showCreateFolderBox} footer={null} onCancel={() => setShowCreateFolderBox(false)}>
				<Spin spinning={isSaving}>
					<div className="mypopu">
						<div className="con">
							<input style={{ width: "96%", padding: "0 2%", borderRadius: 48, height: 48, lineHeight: 48, border: "1px solid rgb(195, 195, 195)", backgroundColor: "transparent", outline: "none" }} onInput={onInputFolderName} onKeyUp={onInputFolderName} onChange={onInputFolderName} className="input1" type="text" placeholder="Folder Name" />
						</div>
						<div className="footer">
							<span className="btn btn-primary" onClick={onCreateFolderSubmit}>
								Confirm
							</span>
							<span onClick={() => setShowCreateFolderBox(false)} className="btn btn-default">
								Cancel
							</span>
						</div>
					</div>
				</Spin>
			</Modal>
		</div>
	);
}

export default styled(Main)`
	display: block;
	width: 880px;
	overflow: hidden;
	margin: 20px auto;
    .btn-back{
        height:30px;
        margin-bottom:10px;
        display: flex;
        flex-direction: row;
        align-items: center;
        gap:10px;
        cursor: pointer;
        &::before{
            content:"";
            background-image: url("/img/back.svg");
            background-repeat: no-repeat;
            background-position: center;
            background-size: 30px;
            width:30px;
            height:30px;
            display: block;
            overflow: hidden;
        }
    }
	@keyframes rotate {
		from {
			transform: rotate(0deg);
		}
		to {
			transform: rotate(360deg);
		}
	}
	.video-box {
		width: 100%;
		background-color: #000;
		border-radius: 20px;
		overflow: hidden;
		video {
			width: 100%;
		}
		.video-msg {
			width: 100%;
			height: 20px;
			line-height: 20px;
			color: #fff;
			font-size: 13px;
			text-indent: 20px;
			padding-bottom: 20px;
		}
	}

	.music-box {
		display: flex;
		justify-content: center;
		align-items: center;
		flex-direction: column;
		.cp {
			width: 300px;
			height: 300px;
			background: linear-gradient(180deg, rgba(255, 246, 12, 1) 0%, rgba(208, 50, 165, 1) 100%);
			display: flex;
			justify-content: center;
			align-items: center;
			border-radius: 20px;
			margin-bottom: 10px;
			img {
				width: 200px;
				height: 200px;
				display: block;
				overflow: hidden;
				border-radius: 100%;
				animation: rotate 6s infinite linear;
				transform-origin: center center;
			}
		}
	}
	.image-box {
		width: 100%;
		height: auto;
		border-radius: 20px;
		overflow: hidden;
		display: block;
		text-align: center;
		img {
			max-width: 100%;
		}
	}
	.app-box {
		div {
			width: 170px;
			height: 170px;
			background-color: #eee;
			background-image: url("/img/rar.png");
			background-position: center;
			background-repeat: no-repeat;
			background-size: 50px;
			border-radius: 20px;
			margin: 0 auto;
		}
	}
	.app-box333{
		.react-doc-viewer{
			background-color: #e9e9e9;
		}
		iframe{
			min-height: 1000px;
		}
	}
	.unknow-box {
		div {
			width: 170px;
			height: 170px;
			background-color: #eee;
			background-image: url("/img/unknow.png");
			background-position: center;
			background-repeat: no-repeat;
			background-size: 50px;
			border-radius: 20px;
			margin: 0 auto;
		}
	}
	.title {
		width: 100%;
		line-height: 40px;
		font-size: 16px;
		font-weight: bold;
	}
	.auther-box {
		display: flex;
		flex-direction: row;
		height: 90px;
		align-items: center;
		.avtho {
			width: 40px;
			height: 40px;
			display: block;
			overflow: hidden;
			border-radius: 100%;
			background-color: #000;
			text-align: center;
			line-height: 40px;
			color: #fff;
			font-size: 18px;
		}
		.addr {
			flex: 1;
			height: 50px;
			line-height: 50px;
			text-indent: 10px;
		}
		.btns {
			height: 50px;
			display: flex;
			flex-direction: row;
			align-items: center;
			span,
			a {
				height: 30px;
				line-height: 30px;
				font-size: 13px;
				background-color: #f0f0f0;
				text-align: center;
				background-repeat: no-repeat;
				background-size: 14px;
				margin: 0 4px;
				border-radius: 6px;
				background-position: 16px;
				text-indent: 25px;
				cursor: pointer;
			}
			span:hover,
			a:hover {
				background-color: #cfcfcf;
			}
			.btn1 {
				width: 142px;
				background-image: url(/img/cloud.png);
				background-position: 15px;
			}
			.btn2 {
				width: 95px;
				background-image: url(/img/dowload.svg);
				background-position: 12px;
			}
			.btn3 {
				width: 80px;
				background-image: url(/img/share.svg);
				background-position: 15px;
			}
		}
	}
	.more-info {
		background-color: #eee;
		padding: 10px;
		border-radius: 10px;
		font-size: 14px;
		div {
			line-height: 24px;
		}
		.l2 {
			padding-left: 28px;
			background-image: url(/img/icon_cess.png);
			background-position: left;
			background-repeat: no-repeat;
			background-size: 19px;
			color: #737373;
			line-height: 32px;
		}
	}
`;
